package com.mjf.cjt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chanjet.openapi.sdk.java.exception.ChanjetApiException;
import com.mjf.cjt.domain.TmAccountDicEntity;
import com.mjf.cjt.mapper.TmAccountDicMapper;
import com.mjf.cjt.service.AsyncTMService;
import com.mjf.cjt.service.TmAccountDicService;
import com.mjf.cjt.vo.AccountResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * desc
 * </p>
 *
 * @author chenshoumeng
 * @date 2025/4/13 14:35
 */
@Service
public class TmAccountDicServiceIMpl extends ServiceImpl<TmAccountDicMapper, TmAccountDicEntity> implements TmAccountDicService {


    @Autowired
    private AsyncTMService asyncTMService;

    @Override
    @Transactional
    public void syncAccount() {
        try {
            AccountResultVO accountResultVO = asyncTMService.syncAccount();
            if (accountResultVO != null && accountResultVO.getDataTable() != null && accountResultVO.getDataTable().getRows() != null) {
                List<TmAccountDicEntity> accountEntityList = new ArrayList<>();
                for (AccountResultVO.Row row : accountResultVO.getDataTable().getRows()) {
                    TmAccountDicEntity accountEntity = new TmAccountDicEntity();
                    BeanUtil.copyProperties(row, accountEntity);

                    accountEntity.setAccounttypedtoId(row.getAccounttypedto_id());
                    accountEntity.setAccounttypedtoCode(row.getAccounttypedto_code());
                    accountEntity.setAccounttypedtoName(row.getAccounttypedto_name());
                    accountEntity.setDcdirectionCode(row.getDcdirection_code());
                    accountEntity.setDcdirectionName(row.getDcdirection_name());
                    accountEntity.setDefaultcurrencydtoId(row.getDefaultcurrencydto_id());
                    accountEntity.setDefaultcurrencydtoCode(row.getDefaultcurrencydto_code());
                    accountEntity.setDefaultcurrencydtoName(row.getDefaultcurrencydto_name());

                    accountEntityList.add(accountEntity);
                }
                // 删除已存在数据
                removeByIds(accountEntityList.stream().map(TmAccountDicEntity::getId).collect(Collectors.toList()));
                saveBatch(accountEntityList);
            }
        } catch (ChanjetApiException e) {
            throw new RuntimeException(e);
        }

    }


}
